<?php
/**
 * 退款处理
 *
 *@author  ZhangYe<banfg56@gmail.com>
 *@date    02/22/2017
 */
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;

class RefundController extends BaseController {

	public function index(){
		$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
		$MRefund = D('Admin/Refund');

		$psize = I('get.psize', $this->m_psize,'intval');
		$psize = (!$psize || $psize>20 ) ? $this->m_psize:$psize ;

		$status = I('get.status',-1, 'intval');
		$wheres = array();
		$wheres['_string'] = '1=1';
		$wheres['refund.is_delete'] = array('neq', 1 ); //没有逻辑删除的数据
		if( -1 != $status )
			$wheres['refund.status'] = array('eq', $status );
		$userphone = I('get.userphone','','trim');
		if( $userphone ){
			$maps = array();
			if(strlen($userphone) > 3 && is_numeric($userphone)) {
				$maps['c.phone'] = array('like','%'.$userphone.'%');
			}
			$maps['c.nickname'] = array('like','%'.$userphone.'%');
			$maps['c.customer_code'] = array('like','%'.$userphone.'%');
			$maps['_logic'] = 'OR';
			$wheres['_complex'] = $maps;
				// $wheres['risk.customer_name'] = array('like', $userphone.'%');
		}
		$reason = I('get.reason',-1,'intval');
		if( -1 != $reason ){
			$wheres['reason_id'] = array('eq', $reason );
		}
		$refund_id = I('get.refund_id');
		if($refund_id) 		$wheres['refund.refund_id'] = $refund_id;
		//search time param
		$stime = I('get.start_time','','trim');
		$etime = I('get.end_time','','trim');
		if( $stime && $etime ){
			$tm = strtotime( $stime );
			$stime = date('Y-m-d 00:00:00', $tm );
			$tm = strtotime( $etime );
			$etime = date('Y-m-d 23:59:29', $tm );
			$wheres['refund.create_time'] = array('between', array($stime, $etime ) );
		}
		else if( $stime && !$etime ){
			$tm = strtotime( $stime );
			$stime = date('Y-m-d 00:00:00', $tm );
			$wheres['refund.create_time'] = array('gt', $stime );
		}
		else if( $etime && !$stime ){
			$tm = strtotime( $etime );
			$etime = date('Y-m-d 23:59:29', $tm );
			$wheres['refund.create_time'] = array('lt', $etime );
		}

		//根据业务人员型姓名进行搜索
		$sales = I('get.sales','','trim');
		if( $sales ){
			$MUser = D('Admin/User');
			$whereu = array();
			$whereu['nickname'] = array('like', '%'.$sales.'%');
			$salesSql = $MUser->field("user_id")->where( $whereu )->buildSql();
			$wheres['_string'] = 'refund.sales_id IN '.$salesSql;
		}

		$cnt = $MRefund->join("LEFT JOIN customer c on c.customer_id=refund.customer_id")
					   ->where( $wheres )
					   ->count();

		$Page = new \Common\ORG\Page( $cnt, $psize );
		$dlist = $MRefund->field("refund.refund_id,refund.phone,refund.customer_id,refund.reason_id,refund.waibu_tousu,
			refund.sales_id,refund.sales_sector,refund.sales_manager,refund.sales_subcompany,refund.pay_name,
			refund.pay_mount,refund.pay_way,refund.pay_time,refund.sign_status,refund.contract_recycle,refund.invoice_recycle,
			refund.complain_status,refund.creator,refund.complain_end,refund.payee_name,refund.payee_account,refund.payee_way,
			refund.create_time,refund.remark as ref_remark,refund.status,refund.finance_audit_msg,refund.is_delete,
			s.sector_name as company,m.nickname as manager_name,u.nickname as sales_name,c.nickname,
			n.detail_name as reason,c.customer_code,c.mount,c.remark")
						 ->join("LEFT JOIN customer c on c.customer_id=refund.customer_id",'LEFT')
						 ->join("LEFT JOIN sector s on refund.sales_subcompany=s.sector_id",'LEFT')
						 ->join("LEFT JOIN user u on u.user_id=refund.sales_id",'LEFT')
						 ->join("LEFT JOIN user m on m.user_id=refund.sales_manager",'LEFT')
						 ->join("LEFT JOIN sys_param_detail n on n.sys_param_detail_id = refund.reason_id",'LEFT')
						 ->where( $wheres )
						 ->order("refund.create_time desc ")
						 ->limit($Page->firstRow.','.$Page->listRows )
						 ->select();

		foreach ($dlist as &$vk) {
			$vk['show_phone'] = phone_mask($vk['phone']);
		}

		if( $dlist ){
			$res['rcode'] = 1;
			$res['data'] = $dlist;
			$res['pall'] =  $Page->getTotalPages();
			$res['p'] = $Page->nowPage;
			$res['psize'] = $psize;

		}else{
			$res['msg'] = "退款记录暂时没有数据";
		}

		e_json( $res );
	}

	/**页面表单获取配置选项*/
	public function options(){

		$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
		$MSector = D('Sector','Service','Admin');
		$MRefund = D('Refund','Service','Admin');
		$dataSub = $MSector->getSubCompany("sector_id,sector_name");
		$data['subcompany'] = $dataSub['data'];
		$data['reasons'] = $MRefund->reasons('REFUND_REASON');
		$data['waibu'] = $MRefund->reasons('WAIBU_TOUSU');
		//从系统参数表里面获取退款原因
		$res['data'] = $data;

		e_json( $res );
	}

	/*根据输入客户姓名或者电话号码匹配客户信息与合同信息*/
	public function customer(){
		if( IS_POST ){
			$userphone = I('post.userphone','','trim');
			$MRefund = D('Refund','Service','Admin');
			$dfind = $MRefund->customer( $userphone );
			// if( $dfind && $dfind['rcode'] ==  1){ //获取客户信息信息
				// $dcontract = $MRefund->contract( $dfind['data']['customer_id'], 5);
				// if( $dcontract )
				// 	$dfind['contracts'] = $dcontract['data'];
				// else
				// 	$dfind['contracts'] = FALSE;
			// }
			e_json( $dfind );
		}
	}

	/*添加*/
	public function add(){
		$res = array('rcode'=>1,'data'=>NULL, 'msg'=> 'OK');
		$MTags = M('\Admin\Model\TagsModel:Tag','customer_');
		$uinfo =$MTags->index();
		if( IS_POST ){
			$data = $_POST['data'];
			// $subCompany = I('post.sales_company');
			$add_data = array();
			$add_data['phone'] = $data['phone'];
			$add_data['customer_id'] = $data['customer_id'];
			$add_data['sales_id'] = $data['sales_id'];
			$add_data['sales_manager'] = $data['sales_manager'];
			$add_data['sales_subcompany'] = $data['sales_subcompany'];
			$reason = $data['reason'];
			$add_data['reason_id'] = $reason ? $reason['id'] : NULL; //
			$add_data['pay_mount'] = $data['pay_mount'];
			$add_data['creator'] = $uinfo['user_id'];
			$add_data['remark'] = $data['remark'];
			$waibu_tousu = $data['waibu_tousu'];
			$add_data['waibu_tousu'] = $waibu_tousu?$waibu_tousu['id']:NULL;
			//合同、发票、投诉情况
			$add_data['contract_recycle'] = $data['contract_status'];
			$add_data['invoice_recycle'] = $data['invoice_status'];
			$add_data['complain_status'] = $data['complain_status'];
			$add_data['sign_status'] = $data['sign_status'];
			//退款账户信息
			$add_data['payee_name'] = $data['payee_name'];
			$add_data['payee_account'] = $data['payee_account'];
			$add_data['payee_way'] = $data['payee_way'];
			//call refund service
			$delivery = $_POST['delivery'];
			$add_delivery = array();
			foreach($delivery as $key => $value) {
				$add_delivery[$key]['recipients'] = $value['recipients'];
				$add_delivery[$key]['phone'] = $value['phone'];
				$add_delivery[$key]['address'] = $value['address'];
				$add_delivery[$key]['delivery_num'] = $value['delivery_num'];
				$add_delivery[$key]['send_way'] = $value['send_way'];
				$add_delivery[$key]['send_time'] = $value['send_time'];
				$add_delivery[$key]['remark'] = $value['remark'];
				$add_delivery[$key]['sales_manager'] = $data['sales_manager'];
				$add_delivery[$key]['sales_subcompany'] = $data['sales_subcompany'];
				$add_delivery[$key]['customer_id'] = $data['customer_id'];
				$add_delivery[$key]['sales_id'] = $data['sales_id'];
				$add_delivery[$key]['source_type'] = 3;
				$add_delivery[$key]['status'] = 10;
			}

			$refund = $_POST['refund'];
			$add_refund = array();
			foreach($refund as $key => $value) {
				$add_refund[$key]['pay_id'] = $value['pay_id'];
				$add_refund[$key]['pay_mount'] = $value['pay_mount'];
				$add_refund[$key]['refund_mount'] = $value['refund_mount'];
			}

			$MRefund  = D('Refund','Service', 'Admin');
			$addRes = $MRefund->add( $add_data,$add_delivery,$add_refund);

			if( $addRes && !$addRes['rcode'] ){
				$res['rcode'] = 0;
				$res['msg'] = $addRes['msg'];
			}
			else{
				$res['data'] = $addRes['data'];
			}
			e_json( $res );
		}
	}

	/*编辑*/
	public function edit(){
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$MRefund = D('Refund','Service','Admin');

		if( IS_GET ){
			$id = I('get.id', 0, 'intval');

			$detail = $MRefund->detail( $id );
			// if( $detail && $detail['detail']['status'] == \Admin\Model\RefundModel::STATUS_INIT ){
				$res['rcode'] = 1;
				$res['msg'] = 'OK';
				$res['data'] = $detail['detail'];
				$res['delivery'] =$detail['delivery'];
				$res['refund'] =$detail['refund'];
			// }
			// else{
			// 	$res['msg'] = "退款数据无法编辑";
			// }
		}
		else{
			$data = $_POST['data'];

			$id = $data['id'];
			$reason = $data['reason'];
			$edit_data = array();
			$edit_data['pay_mount'] = $data['pay_mount'];
			$edit_data['remark'] = $data['remark'];
			$edit_data['payee_name'] = $data['payee_name'];
			$edit_data['payee_account'] = $data['payee_account'];
			$edit_data['payee_way'] = $data['payee_way'];
			$edit_data['reason_id'] = $reason ? $reason['id'] : NULL; //
			$edit_data['invoice_recycle'] = $data['invoice_recycle'];
			$edit_data['contract_recycle'] = $data['contract_recycle'];
			$edit_data['sign_status'] = $data['sign_status'];
			$edit_data['sales_id'] = $data['sales_id'];
			$edit_data['customer_id'] = $data['customer_id'];
			$waibu_tousu = $data['waibu_tousu'];
			$edit_data['waibu_tousu'] = $waibu_tousu?$waibu_tousu['id']:NULL;

			$refund = $_POST['refund'];
			$delivery = $_POST['delivery'];
			$res = $MRefund->edit( $id, $edit_data ,$refund,$delivery);
		}

		e_json( $res );
	}

	/**取消退款申请*/
	public function cancel(){
		if( IS_POST ){
			$MRefund = D('Refund', 'Service', 'Admin');
			$id = I('post.id', 0, 'intval');

			$dres = $MRefund->cancel( $id );

			e_json( $dres );
		}
	}

	/*退款信息导出*/
	public function export_popup() {
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');

		$status = I('get.status',-1, 'intval');
		$wheres = array();
		$wheres['_string'] = '1=1';
		$wheres['refund.is_delete'] = array('neq', 1 ); //没有逻辑删除的数据
		if( -1 != $status )
			$wheres['refund.status'] = array('eq', $status );
		$userphone = I('get.userphone','','trim');
		// if( $userphone ){
		// 	if( preg_match('#^1[0-9]{10}$#', $userphone) ){
		// 		$wheres['c.phone'] = array('eq', $userphone);
		// 	}
		// 	else
		// 		$wheres['c.nickname'] = array('like', $userphone.'%');
		// }
		if( $userphone ){
			$maps = array();
			if(strlen($userphone) > 3 && is_numeric($userphone)) {
				$maps['c.phone'] = array('like','%'.$userphone.'%');
			}
			$maps['c.nickname'] = array('like','%'.$userphone.'%');
			$maps['c.customer_code'] = array('like','%'.$userphone.'%');
			$maps['_logic'] = 'OR';
			$wheres['_complex'] = $maps;
				// $wheres['risk.customer_name'] = array('like', $userphone.'%');
		}
		$reason = I('get.reason',-1,'intval');
		if( -1 != $reason ){
			$wheres['reason_id'] = array('eq', $reason );
		}
		$refund_id = I('get.refund_id','','intval');
		if($refund_id) 		$wheres['refund.refund_id'] = $refund_id;
		//search time param
		$stime = I('get.start_time','','trim');
		$etime = I('get.end_time','','trim');
		if( $stime && $etime ){
			$tm = strtotime( $stime );
			$stime = date('Y-m-d 00:00:00', $tm );
			$tm = strtotime( $etime );
			$etime = date('Y-m-d 23:59:29', $tm );
			$wheres['refund.create_time'] = array('between', array($stime, $etime ) );
		}
		else if( $stime && !$etime ){
			$tm = strtotime( $stime );
			$stime = date('Y-m-d 00:00:00', $tm );
			$wheres['refund.create_time'] = array('gt', $stime );
		}
		else if( $etime && !$stime ){
			$tm = strtotime( $etime );
			$etime = date('Y-m-d 23:59:29', $tm );
			$wheres['refund.create_time'] = array('lt', $etime );
		}

		//根据业务人员型姓名进行搜索
		$sales = I('get.sales','','trim');
		if( $sales ){
			$MUser = D('Admin/User');
			$whereu = array();
			$whereu['nickname'] = array('like', '%'.$sales.'%');
			$salesSql = $MUser->field("user_id")->where( $whereu )->buildSql();
			$wheres['_string'] = 'refund.sales_id IN '.$salesSql;
		}

		// if( IS_POST ){
			// $stime = I('post.start_time', '', 'trim');
			// $etime = I('post.end_time', '', 'trim');
			$MRefund = D('Admin/Refund');
			// $wheres['_string'] = '1=1';
			import("Common.ORG.Excel");
			$SExcel = new \Common\ORG\Excel();
			$SSheet = new \Common\ORG\Sheet("退款数据");

			$dataList =  $MRefund->field("refund.*,c.location,s.sector_name as company,m.nickname as manager_name,u.nickname as sales_name,c.nickname as customer_name,n.detail_name as waibu_tousu_show,o.detail_name as reason_show,
											CASE WHEN refund.contract_recycle = 0 THEN '客户没有签订合同'
												 WHEN refund.contract_recycle = 1 THEN '合同没有收回'
												 WHEN refund.contract_recycle = 2 THEN '合同已经收回'
												 ELSE '未知' END AS contract_recycle_show,
											CASE WHEN refund.sign_status = 0 THEN '未处理'
												 WHEN refund.sign_status = 1 THEN '暂不寄'
												 WHEN refund.sign_status = 2 THEN '等待寄回'
												 WHEN refund.sign_status = 3 THEN '签完'
												 WHEN refund.sign_status = 4 THEN '作废重签'
												 WHEN refund.sign_status = 5 THEN '拒签'
												 ELSE '未知' END AS sign_status_show,
											CASE WHEN refund.invoice_recycle = 0 THEN '客户没有开发票'
												 WHEN refund.invoice_recycle = 1 THEN '客户发票没有收回'
												 WHEN refund.invoice_recycle = 2 THEN '客户发票已经收回'
												 ELSE '未知' END AS invoice_recycle_show,
											CASE WHEN refund.status = 0 THEN '待处理'
												 WHEN refund.status = 10 THEN '已取消'
												 WHEN refund.status = 20 THEN '申请失败'
												 WHEN refund.status = 30 THEN '风控确认'
												 WHEN refund.status = 31 THEN '退款失败'
												 WHEN refund.status = 40 THEN '退款成功'
												 ELSE '未知' END AS status_show
									")
							 ->join("LEFT JOIN customer c on c.customer_id=refund.customer_id")
							 ->join("LEFT JOIN sector s on refund.sales_subcompany=s.sector_id")
							 ->join("LEFT JOIN user u on u.user_id=refund.sales_id")
							 ->join("LEFT JOIN user m on m.user_id=refund.sales_manager")
							 ->join("LEFT JOIN sys_param_detail n on n.sys_param_detail_id = refund.waibu_tousu")
							 ->join("LEFT JOIN sys_param_detail o on o.sys_param_detail_id = refund.reason_id")
							 ->where( $wheres )
							 ->order("refund.create_time desc")
							 ->select();

			/*判断是否拥有高级导出功能*/
			$MRight = D('User','Service','Admin');
			$dright = $MRight->authWithKey($this->m_user['user_id'],'REFUND_GAOJI');

			if($dright['rcode'] || $this->m_is_admin) {
				$column = array('编号','申请时间','客户姓名','电话','归属地','业务员','经理','团队','交款总金额','退款金额','退款原因','合同是否回收','退款协议是否回收','发票是否回收','是否外部投诉','备注','状态');
			} else {
				$column = array('编号','申请时间','客户姓名','归属地','业务员','经理','团队','交款总金额','退款金额','退款原因','是否外部投诉','备注','状态');
			}
			$SSheet->setColumn( $column );
			$SRefund = D('Refund','Service','Admin');
			$_dataOption = $SRefund->reasons();
			$dataOption = array();
			foreach($_dataOption as &$v ){
				$dataOption['k'.$v['id']] = $v['name'];
			}
			if( $dataList ){
				foreach($dataList as $key => $vd ){
					/*获取客户付款总额*/
					$where = array();
					$where['customer_id'] = $vd['customer_id'];
					$where['audit_res'] = 1;
					$where['record_status'] = 1;
					$mlist = M('pay_record')->field("sum(pay_mount) as achieve")->where($where)->select();

					$row = array();
					$row[] = $vd['refund_id'];
					$row[] = $vd['create_time'];
					$row[] = $vd['customer_name'];
					if($dright['rcode']  || $this->m_is_admin) {
						$row[] = $vd['phone'];
					}
					$row[] = $vd['location'];
					$row[] = $vd['sales_name'];
					$row[] = $vd['manager_name'];
					$row[] = $vd['company'];
					$row[] = $mlist[0]['achieve'];
					$row[] = $vd['pay_mount'];
					$row[] = $vd['reason_show'];
					if($dright['rcode'] || $this->m_is_admin) {
						$row[] = $vd['contract_recycle_show'];
						$row[] = $vd['sign_status_show'];
						$row[] = $vd['invoice_recycle_show'];
					}
					$row[] = $vd['waibu_tousu_show'];
					$row[] = $vd['remark'];  // //0、申请中，未处理；1、退款成功；2、申请失败；3、取消
					$row[] = $vd['status_show'];
					$SSheet->addRow( $row );
				}
			}

			$exportData = $SExcel->add_sheet( $SSheet)->export_sheet("退款数据导出");
			if( $exportData['rcode'] ){
				$exportData['name'] = basename( $exportData['data']['view_path'] );
				$exportData['excel'] = file_get_contents( $exportData['data']['real_path'] );
				echo $exportData['excel'];
				exit();
				// $res['rcode'] = 1;
				// $res['data'] = 'www.crm3.com/'.$exportData['data']['view_path'];
 			}
		// }
			// e_json( $res );
	}

	public function confirm()
	{
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'OK');
		$MRefund  = D('Refund','Service', 'Admin');

		if( IS_GET ){
			$id = I('get.id', 0, 'intval');

			$detail = $MRefund->detail( $id );
			if( $detail ){
				$res['rcode'] = 1;
				$res['msg'] = 'OK';
				$res['data'] = $detail['detail'];
				$res['contracts'] =$detail['contracts'];
			}
			else{
				$res['msg'] = "退款数据获取失败";
			}
		}
		else{
			$refund_id = I('post.id','0','intval');
			$refund_confirm = I('post.approve', FALSE, 'intval');
			$extdata = array();
			if( $refund_confirm === FALSE ){
				$res['msg'] = L('PARAM_WRONG');
			}
			else{
				// if( $refund_confirm == 1){
					// $extdata['contract_recycle'] = I('post.contract_status',NULL ,'intval');
					// $extdata['invoice_recycle'] = I('post.invoice_status', NULL, 'intval');
					// $extdata['complain_status'] = I('post.complain_status', NULL, 'intval');
					// $extdata['sign_status'] = I('post.sign_status', NULL, 'intval');
					// $extdata['contract_id'] = I('post.contract_id', NULL, 'intval');
					// $extdata['customer_id'] = I('post.customer_id', NULL, 'intval');
					$remark = I('post.remark','','trim');
					if( $remark )
						$extdata['remark'] = $remark;
				// }
				$dataConfirm = $MRefund->confirm( $refund_id, $refund_confirm, $extdata );
				if( $dataConfirm && $dataConfirm['rcode'] ){
					$res['rcode'] = 1;
					$res['msg'] = 'OK';
				}else{
					$res['msg'] = $dataConfirm['msg'];
				}
			}
		}

		if( $dataConfirm && $dataConfirm['rcode'] ){
				$res['rcode'] = 1;
				$res['data'] = $dataConfirm['data'];
				$res['msg'] = 'OK';
			}
			else
				$res['msg'] = $dataConfirm['msg'];

		e_json( $res );
	}

	//删除退款信息
	public function delete()
	{
		if( IS_POST ){
			$refund_id = I('post.id',0,'intval');
			$MRefund  = D('Refund','Service', 'Admin');

			$dres = $MRefund->delete( $refund_id );

			e_json( $dres );
		}
	}
}